<template>
	<view>
		<nav-bar title="立即充电"></nav-bar>
		<image :style="{'top':navHeight+'px'}" class="top-bg" src="https://oss.jxhecong.com/v2/image/bike_top_bg@2x.png"></image>
		<scroll-view :style="{'margin-top':(navHeight+10)+'px'}">
			<view class="card">
				<car-device-cell :data="socket"></car-device-cell>
				<view class="card-footer">
					<view style="margin-bottom:10rpx;">充电场站：{{socket.chargingGroupName}}</view>
					<view>所在地址：{{socket.chargingGroupAddress}}</view>
				</view>
			</view>
			<view class="card box" style="margin-top:24rpx;padding-bottom:0rpx;">
				<view style="color:#303133;font-size:24rpx;">当前计费时段：{{currentInterval.startTime}} ~ {{currentInterval.endTime}}</view>
				<view class="flex">
					<view style="color: #FA3534;font-size: 42rpx;font-weight: bold;">￥{{currentInterval.totalMoney}}</view>
					<view class="item-cell" @click.stop="ele_Click">
						<text style="color:#6ABF6C;font-size:28rpx;">电价详情</text>
						<image style="width:24rpx;height:24rpx;" src="https://images.zjqiyuan.cn/image/arrow_gray@2x.png"></image>
					</view>
				</view>
				<view style="color:#909399;font-size: 24rpx;">电费：{{currentInterval.amount}}元/度    服务费：{{currentInterval.serviceAmount}}元/度</view>
				<view class="car-footer">
					<image src="https://images.zjqiyuan.cn/image/port@2x.png"></image>
					<text>停车收费：以物业实际收费为准</text>
				</view>
			</view>
			<view class="card box" style="margin-top:24rpx;">
				<select-socket-or-mode 
				title="请选择充值金额" 
				@selectChange="selectChange" 
				:rowCount="3"
				:current="currentIndex"
				:dataList="dataList"></select-socket-or-mode>
			</view>
			<view class="card" style="margin-top:24rpx;">
				<select-pay-method @payMethodChange="payMethodChange" :balance="userInfo.totalMoney"></select-pay-method>
			</view>
			<!-- <view class="card box" style="margin-top:24rpx;">
				<text>钱包余额</text>
				<text class="remain">（{{userInfo.totalMoney}}）</text>
			</view> -->
		</scroll-view>
		<view style="height:150rpx;"></view>
		<view class="footer">
			<view class="scan" @click.stop="charge_Click">
				<text>开始充电</text>
			</view>
		</view>
		<power-pop-view ref="powerPopView"></power-pop-view>
		<recharge-pop-view ref="rechargePopView"></recharge-pop-view>
		<charging-progress-pop-view :show="showCharging" :percent="percent"></charging-progress-pop-view>
	</view>
</template>

<script>
	var globalData = getApp({
		allowDefault: true
	}).globalData
	import navBar from '../components/navBar.vue'
	import carDeviceCell from '../components/carDeviceCell.vue'
	import selectSocketOrMode from '../components/selectSocketOrMode.vue'
	import selectPayMethod from '../components/selectPayMethod.vue'
	import powerPopView from '../site/powerPopView.vue'
	import chargingProgressPopView from '../components/chargingProgressPopView.vue'
	import rechargePopView from './rechargePopView.vue'
	import * as chargeApi from '../../api/charge/index.js'
	import * as userApi from '../../api/user/index.js'
	var timer = null
	var resultTimer = null
	export default{
		components:{navBar,carDeviceCell,selectSocketOrMode,selectPayMethod,powerPopView,chargingProgressPopView, rechargePopView},
		data(){
			return{
				id:'',
				navHeight:0,
				dataList:[],
				currentIndex:0,
				showCharging:false,
				percent:0,
				payMethod:0,
				socket:{},
				currentInterval:{},
				userInfo:{}
			}
		},
		onUnload() {
			globalData.qrCode=""
			this.clearTimer()
		},
		onHide() {
			this.clearTimer()
		},
		onLoad(options) {
			// #ifdef MP
			let url = ""
			let shellId=""
			let data=""
			// #ifdef MP-WEIXIN
			url = decodeURIComponent(options.q)
			data = url.split('shell=')[1]
			shellId = options.shellId
			// #endif
			// #ifdef MP-ALIPAY
			url = decodeURIComponent(globalData.qrCode)
			data = url.split('shell=')[1]
			shellId = options.shellId
			// #endif
			if (data || shellId) {
				data = data ? data : shellId
				let userInfo=uni.getStorageSync('userInfo')
				if(!userInfo) {
					uni.reLaunch({
						url:'/pages/login/login?type=1&shell=' + data
					})
					return
				}
				this.getChargeIdByQRCode(data,(id)=>{
					this.id=id;
					this.getCarChargingSocketDetail();
					this.getUserInfo()
				})
			} else {
				this.id=options.id;
				this.getCarChargingSocketDetail();
				this.getUserInfo()
			}
			// #endif
			// #ifdef APP-PLUS || APP-PLUS-NVUE
			this.id=options.id;
			this.getCarChargingSocketDetail();
			// #endif
			this.navHeight = globalData.titleHeight;
		},
		onShow() {
			this.getUserInfo()
		},
		methods:{
			ele_Click(){
				uni.navigateTo({
					url:'/pages/site/carElectDetail?id=' + this.socket.chargingGroupId
				})
			},
			selectChange(e){
				this.currentIndex=e.index
			},
			payMethodChange(e){
				this.payMethod=e.method
			},
			getCarChargingSocketDetail() {
				chargeApi.getCarChargingSocketDetail(this.id).then((res)=>{
					this.socket = res.data
					res.data.billingPlans.map((item)=>{
						if (item.billingType != 0) {
							this.$set(item,'name', item.value +'元')
						} else {
							this.$set(item,'name', item.value)
						}
					})
					this.dataList = res.data.billingPlans
					this.currentInterval = res.data.currentInterval
				}).catch((errMsg)=>{
					uni.showToast({
						title:errMsg,
						icon:'none'
					})
				})
			},
			getChargeIdByQRCode(qrcode,callback){
				homeApi.getChargeScan(qrcode).then((res) => {
					typeof callback == 'function'&&callback(res.data.chargingId)
				}).catch((errMsg) => {
					uni.showToast({
						title:errMsg,
						icon:'none'
					})
				})
			},
			processClock(){
				let seconds = 30
				timer = setInterval(()=>{
					seconds = seconds - 0.1
					if (this.percent < 90) {
						this.percent = this.percent + 100 / 300
					}
					if (seconds <= 0) {
						clearInterval(timer)
						clearInterval(resultTimer)
						this.showCharging = false
						this.percent = 0
						uni.showToast({
							title: '充电失败，请再试一次',
							icon: 'none'
						})
					}
				},100)
			},
			
			pollingCharging(orderNumber,callback){
				resultTimer=setInterval(()=>{
					this.getChargeResult(orderNumber,callback)
				},1000)
			},
			
			getChargeResult(orderNumber,callback){
				chargeApi.confirmCarOrderResult(orderNumber).then((res)=>{
					if(res.code == 0){
						console.log('## 确认回复请求 ## ' + res.data)
						this.clearTimer();
						this.getCarChargingSocketDetail()
						typeof callback==='function'&&callback('success')
					}
				}).catch((error)=>{
					this.showCharging = false
					this.percent = 0
					this.clearTimer()
					uni.showToast({
						title:error,
						icon:'none'
					})
				})
			},
			
			clearTimer(){
				clearInterval(timer)
				clearInterval(resultTimer)
			},
			
			endProgerss(orderNumber){
				let duration = 0.2
				let lastPercent = 100 - this.percent
				let endTimer = setInterval(()=>{
					duration = duration - 0.1
					this.percent = this.percent + lastPercent / 2.0
					if (duration < 0) {
						this.showCharging = false
						this.percent = 0
						clearInterval(endTimer)
						uni.navigateTo({
							url: '/pages/order/chargingDetail?deviceType=1&orderNumber='+orderNumber
						})
					}
				},100)
			},
			
			charge_Click(){
				if(this.dataList.length==0){
					uni.showToast({
						title:'请选择充值金额',
						icon:'none'
					})
					return
				}
				this.showCharging = true;
				this.percent = 0;
				this.processClock();
				console.log(this.dataList[this.currentIndex])
				chargeApi.startCarCharge(this.dataList[this.currentIndex].id,this.dataList[this.currentIndex].billingType,this.dataList[this.currentIndex].value,this.socket.id).then((res)=>{
					console.log(res)
					if(res.code == 1041) {
						this.showCharging = false
						this.percent = 0
						this.clearTimer();
						uni.showModal({
							title:'余额不足，请充值',
							success: (res) => {
								if(res.confirm) {
									this.$refs['rechargePopView'].open(this.socket.chargingGroupId)
								}
							}
						})
						
					} else {
						let orderNumber=res.data.orderNumber;
						this.pollingCharging(orderNumber,()=>{
							this.endProgerss(orderNumber)
						})
					}
				}).catch((errorMsg)=>{
					this.showCharging = false
					this.percent = 0
					this.clearTimer();
					uni.showToast({
						title:errorMsg,
						icon:'none'
					})
				})
			},
			getUserInfo(){
				let userInfo=uni.getStorageSync('userInfo')
				if (userInfo) {
					userApi.getUserInfo().then((res) => {
						if (res.code == 0) {		
							this.userInfo = res.data
						}		
					}).catch((errMsg) => {
					
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.top-bg{
		position: fixed;
		left:0rpx;
		right:0rpx;
		height:112rpx;
		width:100%;
		z-index: 0;
	}
	.card{
		position: relative;
		background: #FFFFFF;
		box-shadow: 0px 1px 4px 0px rgba(0, 0, 0, 0.06);
		border-radius: 9px;
		margin-left:30rpx;
		margin-right:30rpx;
		overflow: hidden;
	}
	.box{
		padding:30rpx;
	}
	.card-footer{
		padding:24rpx 30rpx;
		view{
			color:#606266;
			font-size:24rpx;
		}
	}
	.item-cell{
		display: flex;
		justify-content: flex-start;
		align-items: center;
		margin-top:24rpx;
	}
	.car-footer{
		height:64rpx;
		display: flex;
		justify-content: flex-start;
		align-items: center;
		border-top: solid 1rpx #DCDFE6;
		margin-top:18rpx;
		image{
			width:36rpx;
			height:36rpx;
		}
		text{
			color:#606266;
			font-size:24rpx;
			margin-left:12rpx;
		}
	}
	.flex{
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.footer{
		position: fixed;
		left:0rpx;
		right:0rpx;
		bottom:0rpx;
		height:116rpx;
		background-color:#FFFFFF;
		display: flex;
		justify-content: center;
		align-items: center;
	}
	.scan{
		background: #6ABF6C;
		box-shadow: 0px 1px 2px 0px rgba(8, 139, 120, 0.3);
		height:90rpx;
		border-radius:45rpx;
		display: flex;
		width:100%;
		justify-content: center;
		align-items: center;
		margin-left:30rpx;
		margin-right:30rpx;
		image{
			width:42rpx;
			height:42rpx;
		}
		text{
			color:#FFFFFF;
			font-size:36rpx;
			margin-left:24rpx;
		}
	}
</style>
